﻿using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace TestApp
{
    public class BorderMoveBehavior:Behavior<Border>
    {
        protected override void OnAttached()
        {
            //给控件对象进行多个事件的订阅
            AssociatedObject.MouseLeftButtonDown += MouseDownMethod;
            AssociatedObject.MouseLeftButtonUp += MouseUpMethod;
            AssociatedObject.MouseMove += MouseMoveMethod;
        }

        //父类的Canvas容器对象
        private Canvas parentCanvas = null;
        private bool isDragging = false;
        private Point mouseCurrentPoint;
        private void MouseMoveMethod(object sender, MouseEventArgs e)
        {
            if (isDragging)
            {
                // 相对于Canvas的坐标
                Point point = e.GetPosition(parentCanvas);
                // 设置最新坐标
                AssociatedObject.SetValue(Canvas.TopProperty, point.Y - mouseCurrentPoint.Y);
                AssociatedObject.SetValue(Canvas.LeftProperty, point.X - mouseCurrentPoint.X);
            }
        }

        private void MouseUpMethod(object sender, MouseButtonEventArgs e)
        {
            isDragging = false;
            //锁定鼠标到当前控件对象
            //AssociatedObject.CaptureMouse();
            Mouse.Capture(null);

        }

        private void MouseDownMethod(object sender, MouseButtonEventArgs e)
        {
            isDragging = true;
            // Canvas
            if (parentCanvas == null)
                parentCanvas = (Canvas)VisualTreeHelper.GetParent(sender as Border);
            // 当前鼠标坐标
            mouseCurrentPoint = e.GetPosition(sender as Border);
            // 鼠标锁定
            //AssociatedObject.CaptureMouse();
            Mouse.Capture(AssociatedObject);
        }


        protected override void OnDetaching()
        {
            //给订阅的事件全部取消订阅
            AssociatedObject.MouseLeftButtonDown -= MouseDownMethod;
            AssociatedObject.MouseLeftButtonUp -= MouseUpMethod;
            AssociatedObject.MouseMove -= MouseMoveMethod;
        }
    }
}
